//
//  ComposeViewController.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/25.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    //MARK:关闭
    @objc private func close() {
        print("关闭")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:发送
    @objc private func send() {
        print("发送")
        var urlString = "2/statuses/update.json"
        let parameters = ["access_token": AccountViewModel.sharedAccountViewModel.token,"status": textView.text]
        if picker.imageList.count > 0{
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //调用发布微博的接口
//            let imageData = UIImagePNGRepresentation(picker.imageList.first!)!
            HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //新浪微博的接口只允许上传单张图片  多张图片的接口是高级权限
                //将需要上传的文件转换为二进制的数据 拼接到 formData 中
                //1.data: 需要上传的文件的二进制数据
                //2.name: 服务器的接收字段名
                //3.fileName  服务器存储的文件名称  微博的服务器 会自己重写命名
                //4.mimeType: 文件格式  application/octet-stream: 八进制流 任意文件类型都可以
                //image/jpeg	 图片的文件格式
//                formData.appendPartWithFileData(imageData, name: "pic", fileName: "ooxx", mimeType: "application/octet-stream")
                var index = 0
                for image in self.picker.imageList {
                    let data = UIImagePNGRepresentation(image)!
                    formData.appendPartWithFileData(data, name: "pci", fileName: "fileName\(index)", mimeType: "image/jpeg")
                    index++
                }
                
                }, progress: nil, success: { (_, result) -> Void in
                    print(result)
                    self.close()
                }, failure: { (_, error) -> Void in
                    print(error)
                    //发布微博失败
                    SVProgressHUD.showErrorWithStatus("发布微博失败,请检查网络")
                    
            })
        }else{
            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                if error != nil {
                    //发布微博失败
                    SVProgressHUD.showErrorWithStatus("发布微博失败,请检查网络")
                    return
                }
                self.close()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setTextView()
        setNavBar()
        setToolBar()
        registerNotification()
        setPictureSelector()
    }
    //实现通知方法
    @objc private func keyBoardWillChange(n:NSNotification) {
        print(n)
        //获取动画时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //键盘结束的frame CGRect 是结构体 结构体需要转换成 NSValue对象才能够添加到 字典中
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let height = -KHeight + rect.origin.y
        //在动画闭包中更新约束
        UIView.animateWithDuration(duration) { () -> Void in
            //1.更新约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                //值是负的
                make.bottom.equalTo(height)
            })
            //2.强制刷新页面
            self.view.layoutIfNeeded()
        }

    }
    //MARK:弹出图片选择器
    @objc private func selectPicture() {
        //更新约束
        picker.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(KHeight * 2 / 3)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            //动画中更新约束
            self.view.layoutIfNeeded()
        }
    }
    //注册通知控制键盘
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    private lazy var placeHolder: UILabel = UILabel(text: "输入新鲜事...", fontSize: 18, textColor: UIColor(white: 0.7, alpha: 1))
    //底部工具条
    private lazy var toolBar:UIToolbar = UIToolbar()
    private lazy var textView:UITextView = {
        let t = UITextView()
//        t.text = "输入新鲜事..."
        t.textColor = UIColor.lightGrayColor()
        t.font = UIFont.systemFontOfSize(18)
        t.backgroundColor = UIColor.greenColor()
        //一直可以水平滚动
        t.alwaysBounceVertical = true
        //keyboardDismissMode  这个属性起作用的前提 是滚动视图可以滚动 滚动的时候收回键盘
        t.keyboardDismissMode = .OnDrag
        t.delegate = self
        return t
    }()
    private lazy var picker:PictureSelectorViewController = PictureSelectorViewController()
}
//设置UI
extension ComposeViewController {
    private func setPictureSelector() {
        addChildViewController(picker)
        
        self.view.addSubview(picker.view)
        //移动到图层最上面
        toolBar.bringSubviewToFront(toolBar)
        
        //添加约束
        picker.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(self.view.snp_bottom)
            make.height.equalTo(0)
        }
    }
    //设置底部工具条
    private func setToolBar() {
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
        }
        //设置toolbar 内部的按钮
        var items = [UIBarButtonItem]()
        //配置类型字典
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for item in itemSettings {
            //实例化UIBarButtonItem对象  默认的渲染色 是蓝色 并且不能够设置高亮状态的图片
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, imageName: imageName!)
            let barItem = UIBarButtonItem(customView: btn)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            //将对象添加到数组中
            items.append(barItem)
            
            //添加弹簧的item
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //移除最后一个
        items.removeLast()
        
        //设置工具条的按钮数组对象
        toolBar.items = items
        
    }
    
    //设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        //刚开始发生的用户交互关闭
        navigationItem.rightBarButtonItem?.enabled = false
        //自定义导航条title
        let weiBoTitle = UILabel(text: "发布微博", fontSize: 18, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(text: AccountViewModel.sharedAccountViewModel.userName ?? "", fontSize: 14, textColor: UIColor.lightGrayColor())
        let titleView = UIView(frame:CGRect(x: 0, y: 0, width: 200, height: 40))
        titleView.addSubview(weiBoTitle)
        titleView.addSubview(nameLabel)
        weiBoTitle.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(weiBoTitle.snp_bottom)
        }
        navigationItem.titleView = titleView
    }
    
    private func setTextView() {
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(KHeight / 3)
        }
        
        textView.addSubview(placeHolder)
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
    }
}
extension ComposeViewController:UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //如果用户输入了文本 点亮按钮,隐藏占位文本
        //用户没有输入任何文本  恢复到默认状态
        placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
